<?php


class Data extends \Phalcon\Mvc\Collection
{

    public function initialize()
    {
        $this->setConnectionService('total');
    }

    
    public static function getNextId1($seqName) {
    
        $link = new MongoClient();
        $db = $link->total;

        $res = $db->command(
            array(
                'findandmodify' => 'sequence',
                'query' => array('_id' => $seqName),
                'update' => array('$inc' => array('seq' => 1)),
                'new' => TRUE
                )
            );
        
//var_dump($res);

        // check if there is an error
        if($res["ok"] != 1)
            return false;
        
        return $res["value"]["seq"];
    
    
    
    }

    public static function getNextID($seqName){
     
        $link = new MongoClient();
        $db = $link->total;
        
        $code = <<<FUNC
        funtion(name) { 
            var ret = db.sequence.findAndModify({ 
              query: { _id: name }, 
                update: { $inc: { seq: 1 } }, new: true}); return ret.seq; }";

FUNC;

        $res = $db->execute($code, array($seqName));

var_dump($res);

        return $res['seq'];
    }


}



Class Sequence extends \Phalcon\Mvc\Collection {

    public function initialize()
    {
        $this->setConnectionService('total');
        
    }


    public function getNext($seqName) {
    
        $seq = $this->findById($seqName);
        
        if (empty($seq)) {
            $seq = new Sequence();
            $seq->_id = $seqName;
            $seq->seq = 1;
        }

    
        $seq = $this->findAndModify(
            array('_id' => $name),
            array('$inc' => array("seq" => 1)),
            array( "new" => true,)
        );

        return $seq->seq;
    
    
    }



}